#include <iostream>
#include <memory>
#include <string>
#include "Comm.hpp"
#include "Reactor.hpp"
#include "Socket.hpp"
#include "Connection.hpp"
#include "Factory.hpp"
#include "IOHandler.hpp"
using namespace std;

static const int gbacklog = 32;

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        cout << "Incorrect use, correct use: " << argv[0] << " port" << endl;
        return 1;
    }

    uint16_t port = stoi(argv[1]);

    // 创建Reactor对象
    unique_ptr<Reactor> svr = make_unique<Reactor>();

    // 创建listen套接字
    unique_ptr<Socket> listensock = make_unique<TcpSocket>();
    listensock->BuildListenSock(port, gbacklog);
    // listensockfd设置为非阻塞
    SetNonBlock(listensock->GetSockFd());

    // 创建Connection对象
    unique_ptr<Factory> factory = make_unique<Factory>();
    Connection *listenconn = factory->BuildListenConn(listensock->GetSockFd(), EPOLLIN | EPOLLET, svr.get(), IOHandler::Accept);
    if (!listenconn)
    {
        LOG(Abnormal, "Failed to create listener object\n");
        return 2;
    }

    svr->Init(listenconn);

    svr->Dispatcher();

    return 0;
}